import React, { Component, Suspense } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import download from '@/utils/download';
import PageLoading from '@/components/PageLoading';
import dataTime from '../../../utils/dataTime';
import { FormattedMessage } from 'umi-plugin-react/locale';
import UpDownCharacter from '../../../modules/UpDownCharacter';
import { Row, Col, Card, Icon, Table, Form, Spin, Modal, Button, message, Tabs, DatePicker, Select, Input, Tooltip, Drawer, Pagination } from 'antd';
import styles from './index.less';
import EditQa from '../../KnowledgeManagement/Overview/editQa';
import ContextModal from '@/utils/contextModal';
import { doChatRecords } from '@/services/datastatistics';
import tableDataCheck from '@/utils/isBackPrevPage';
import RelatedKnowledgeV2 from '@/utils/RelatedKnowledgeV2';

const EditingKnowledge = React.lazy(() => import('@/pages/KnowledgeManagement/Overview/EditingKnowledge/editingKnowledge'));
const TabPane = Tabs.TabPane;
const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY/MM/DD';
const Option = Select.Option;
const Search = Input.Search;
const MyIcon = Icon.createFromIconfontCN({
	scriptUrl: '//at.alicdn.com/t/font_1131883_8lpmy5tq6hn.js', // 在 iconfont.cn 上生成
});
@connect(({ process, loading }) => ({
	process,
	loading: loading.effects['waitingLearningIssue/fetch'],
}))
class ModelGeneration extends Component {
	constructor(props) {
		super(props);
		this.state = {
			loginjqr: false,
			logins: true,
			qaListTable: [],
			total2: '',
			knowledgeList: [],
			upDownDate: [],
			total: '',
			beginTime: '',
			overTime: '',
			total: '',
			login: false,
			dataSource: [],
			pageSize: 15,
			page: 1,
			selectedRowKeys: [],
			electa: 'time',
			electb: 'false',
			portJudge: true,
			break: false,
			field: '1',
			question: '',
			ignored: false,
			order: 'time',
			asc: 'desc',
			seek: '',
			zuid: '',
			shutRelevance: false,
			showModel1: false,
			numberRadio: '1',
			pageSizetwo: 10,
			pagetwo: 1,
			nodeId: '',
			nodeIdName: '所有分类',
			close: false,
			qaId: '',
			isUpdate: false,
			aALeng: '',
			glLeng: 10,
			unknownId: '',
			unresolvedId: '',
			currentQaId: '',
			currentQuestion: '',
			contextModalVisible: false,
			contextMessage: [],
			isDownloading: false,
		};
	}

	componentWillMount() {
		let sysTime = dataTime.formatDate(new Date().getTime()); // 初始时间
		let toTime = moment().subtract('days', 7).format('YYYY/MM/DD');
		this.setState(
			{
				beginTime: toTime.replace(/\//g, '-'),
				overTime: sysTime.replace(/\//g, '-'),
			},
			() => {
				this.getFtch();
			}
		);
	}

	// eslint-disable-next-line react/sort-comp
	fetch = (query, ignored, from, to, page, limit, order, sort) => {
		this.setState({ login: true });
		const { dispatch, currentUser } = this.props;
		this.reqRef = requestAnimationFrame(() => {
			dispatch({
				type: 'waitingLearningIssue/fetchMl',
				payload: { query, ignored, from, to, current: this.state.page, size: limit, order, sort },
				callback: res => {
					console.log(res);
					let temp = res.records;
					temp.map((item, index) => {
						item['key'] = index;
						item['time'] = Number(item.updateTime);
					});
					this.props.totald(Number(res.total));
					this.setState({ dataSource: temp, selectedRowKeys: [], total: res.total, selectedRows: null, login: false, logins: true, });
				},
			});
		});
	};

	getFtch() {
		const { seek, beginTime, overTime, page, pageSize, order, asc } = this.state;
		this.fetch(seek, this.state.break, beginTime, overTime, page, pageSize, order, asc);
	}

	componentDidMount() {
		this.props.onRef(this);
	}

	// 日期选择｛开始日期——结束日期｝
	onChange = (date, dateString) => {
		if (date && dateString) {
			this.setState({
				beginTime: dateString[0].replace(/\//g, '-'),
				overTime: dateString[1].replace(/\//g, '-'),
			});
		} else {
			message.error(`请输入开始至结束日期`);
		}
	};

	// 查看
	handleSubmit = () => {
		const { page, pageSize, order, asc, overTime, beginTime } = this.state;
		if (overTime && beginTime) {
			let userInfo = this.props.form.getFieldsValue(); // 获取数据
			// let usercz = this.props.form.resetFields();   // 重置表单数据
			this.props.form.validateFields((err, values) => {
				if (!err) {
					this.setState({ seek: userInfo.seek, evaluate: userInfo.evaluate, });
					let a = '';
					if (userInfo.lose === 'true') {
						a = true;
						this.setState({ electb: 'true', portJudge: false, break: true, page: 1 }, () => {
							this.fetch(userInfo.seek, a, this.state.beginTime, this.state.overTime, page, pageSize, order, asc);
						});
					} else if (userInfo.lose === 'false') {
						a = false;
						this.setState({ electb: 'false', portJudge: true, break: false, page: 1 }, () => {
							this.fetch(userInfo.seek, a, this.state.beginTime, this.state.overTime, page, pageSize, order, asc);
						});
					}
				}
			});
		} else {
			message.error(`请输入开始至结束日期`);
		}
	};

	newlyAdded = row => {
		this.EditingKnowledge.showEditDrawer(null, row.question, null, '', '', '', 0);
	};

	onClose = (type) => {
		this.setState({ close: false, }, () => {
			const { seek, beginTime, overTime, page, pageSize, order, asc, dataSource } = this.state;
			if (type && type === 'done' && !this.state.break) {
				const newCurrent = tableDataCheck(dataSource, page)
				this.setState({ page: newCurrent }, () => {
					this.fetch(seek, this.state.break, beginTime, overTime, newCurrent, pageSize, order, asc);
				})
			} else {
				this.fetch(seek, this.state.break, beginTime, overTime, page, pageSize, order, asc);
			}
		});
	};

	ignore = item => {
		let its = [];
		its.push(item.question);
		const { dispatch } = this.props;
		const { page, pageSize, order, asc, dataSource } = this.state;
		this.reqRef = requestAnimationFrame(() => {
			dispatch({
				type: 'waitingLearningIssue/fetchMm',
				payload: { questions: its, ignored: this.state.portJudge },
				callback: res => {
					message['success'](`${res.msg}`);
					//判断是否需要加载上一页数据 2022.4.8
					const newCurrent = tableDataCheck(dataSource, page, its)
					this.setState({ page: newCurrent }, () => {
						setTimeout(() => {
							const { seek, beginTime, overTime, page, pageSize, order, asc } = this.state;
							this.fetch(seek, this.state.break, beginTime, overTime, newCurrent, pageSize, order, asc);
						}, 1);
					})
				},
			});
		});
	};

	recovery = item => {
		let its = [];
		its.push(item.question);
		const { dispatch } = this.props;
		const { page, pageSize, order, asc, dataSource } = this.state;
		this.reqRef = requestAnimationFrame(() => {
			dispatch({
				type: 'waitingLearningIssue/fetchMm',
				payload: { questions: its, ignored: this.state.portJudge },
				callback: res => {
					message['success'](`${res.msg}`);
					//判断是否需要加载上一页数据 2022.4.8
					const newCurrent = tableDataCheck(dataSource, page, its)
					this.setState({ page: newCurrent }, () => {
						setTimeout(() => {
							const { seek, beginTime, overTime, page, pageSize, order, asc } = this.state;
							this.fetch(seek, this.state.break, beginTime, overTime, newCurrent, pageSize, order, asc);
						}, 1);
					})
				},
			});
		});
	};

	/**
	 * 打开关联问
	 */
	openRelatedModal = (question, id) => {
		this.setState({ relatedVisible: true, currentQuestion: question, currentQaId: id, }, () => {
			this.RelatedKnowledge.openAndInit([])
		});
	};

	/**
	 * 关闭关联问modal
	 */
	closeRelatedModal = (type) => {
		const { seek, beginTime, overTime, page, pageSize, order, asc, dataSource } = this.state;
		//判断是否需要加载上一页数据 2022.4.8
		const newCurrent = tableDataCheck(dataSource, page)
		this.setState({ page: newCurrent }, () => {
			this.fetch(seek, this.state.break, beginTime, overTime, newCurrent, pageSize, order, asc);
		})
	};

	/**
	 * 获取上下文
	 * @returns {*}
	 */
	getChatRecords = async row => {
		if (row.count > 1) {
			const { beginTime, overTime } = this.state;
			const obj = { question: row.question, from: beginTime, to: overTime, type: 4 };
			this.props.openSessionRecordModal(obj, row)
		} else {
			let res = await doChatRecords({
				sessionId: row.lastChatId,
				time: moment(row.createTime).format('YYYY-MM-DD HH:mm:ss'),
			});
			this.setState({ contextMessage: res, contextModalVisible: true, });
		}
	};

	/**
	 * 关闭上下文
	 * @returns {*}
	 */
	cancelContextModal = () => {
		this.setState({ contextModalVisible: false, contextMessage: [], });
	};

	downloading = () => {
		this.setState({ isDownloading: true, }, () => this.down());
	};

	render() {
		const { getFieldDecorator } = this.props.form;
		return (
			<Suspense fallback={<PageLoading />}>
				<div style={{ padding: '0px 20px 0px 30px' }}>
					<div style={{ marginBottom: 20 }} className={styles.fromColumn}>
						<div>
							<Form className={styles.buttonA} layout="inline">
								<FormItem>
									<RangePicker
										onChange={this.onChange}
										style={{ width: 220 }}
										defaultValue={[
											moment(this.state.beginTime, dateFormat),
											moment(this.state.overTime, dateFormat),
										]}
										format={dateFormat}
									/>
								</FormItem>
								<FormItem>
									{getFieldDecorator('lose', { initialValue: this.state.electb, })(
										<Select style={{ width: 130 }}>
											<Option value="false">未忽略</Option>
											<Option value="true">已忽略</Option>
										</Select>
									)}
								</FormItem>
								<FormItem>
									{getFieldDecorator('seek', { initialValue: '', })(
										<Input placeholder="请输入搜索问题" onPressEnter={this.handleSubmit} />
									)}
								</FormItem>
								<FormItem className="buttonYs">
									<Button onClick={this.handleSubmit} type="primary">查询</Button>
								</FormItem>
							</Form>
						</div>
						<span style={{ display: 'flex', gap: 20, alignItems: 'center' }}>
							<span className="buttonYs">
								<Button onClick={this.downloading} loading={this.state.isDownloading}>导出</Button>
							</span>
							{this.state.electb === 'false' ? (
								<span className="zdyButtonA">
									<Button onClick={this.handleRelete} type="primary" icon="eye-invisible">批量忽略</Button>
								</span>
							) : (
								<span className="zdyButtonA">
									<Button onClick={this.handleRelete} type="primary" icon="eye-invisible">批量恢复</Button>
								</span>
							)}
						</span>
					</div>
					{this.lessdata()}
					<Drawer
						title={<FormattedMessage id="app.overView.editQa" />}
						placement="right"
						closable
						onClose={this.onClose}
						visible={this.state.close}
						width={800}
						destroyOnClose
					>
						<EditQa unresolvedId={this.state.unresolvedId} questions={this.state.qaId} onClose={this.onClose} />
					</Drawer>
					<RelatedKnowledgeV2
						onRef={ref => this.RelatedKnowledge = ref}
						applicationId={''}
						chooseType='radio'
						qaId={this.state.currentQaId}
						question={this.state.currentQuestion}
						refreshList={this.closeRelatedModal}
					/>
					<ContextModal visible={this.state.contextModalVisible} message={this.state.contextMessage} cancelContextModal={this.cancelContextModal} />
					<EditingKnowledge onRef={ref => (this.EditingKnowledge = ref)} refreshList={this.onClose} ifCapacity={true} />
				</div>
			</Suspense>
		);
	}

	handleChange = (pagination, filters, sorter) => {
		if (sorter.columnKey === 'count') {
			if (sorter.order === 'ascend') {
				// 升序
				this.setState({ order: 'count', asc: 'asc' });
				this.fetch(this.state.seek, this.state.break, this.state.beginTime, this.state.overTime, this.state.page, this.state.pageSize, 'count', 'asc');
			};
			if (sorter.order === 'descend') {
				// 降序
				this.setState({ order: 'count', asc: 'desc' });
				this.fetch(this.state.seek, this.state.break, this.state.beginTime, this.state.overTime, this.state.page, this.state.pageSize, 'count', 'desc');
			};
			this.setState({ sortOrder: sorter.order, evaluate: 'count', });
		};
		if (sorter.columnKey === 'createTime') {
			if (sorter.order === 'ascend') {
				// 升序
				this.setState({ order: 'time', asc: 'asc' });
				this.fetch(this.state.seek, this.state.break, this.state.beginTime, this.state.overTime, this.state.page, this.state.pageSize, 'time', 'asc');
			};
			if (sorter.order === 'descend') {
				// 降序
				this.setState({ order: 'time', asc: 'desc' });
				this.fetch(this.state.seek, this.state.break, this.state.beginTime, this.state.overTime, this.state.page, this.state.pageSize, 'time', 'desc');
			};
			this.setState({ sortOrder: sorter.order, evaluate: 'count', });
		}
	};

	down = () => {
		const { dispatch } = this.props;
		const { seek, beginTime, overTime, page, pageSize, order, asc } = this.state;
		let userInfo = this.props.form.getFieldsValue(); // 获取数据
		const data = {
			from: beginTime,
			ignored: userInfo.lose,
			order: order,
			sort: asc,
			to: overTime,
			query: userInfo.seek,
			type: 4,
		};
		dispatch({
			type: 'waitingLearningIssue/dcexportWj',
			payload: data,
			callback: res => {
				setTimeout(() => {
					this.setState({ isDownloading: false });
				}, 500);
				download.byBlob(res.data.blob, res.data.fileName);
			},
		});
	};

	lessdata = () => {
		const { selectedRowKeys } = this.state;
		// 多选
		const rowCheckSelection = {
			type: 'checkbox',
			selectedRowKeys, //告诉插件我们点击的哪一行
			onChange: (selectedRowKeys, selectedRows) => {
				this.setState({ selectedRowKeys, selectedRows: selectedRows, });
			},
		};
		const columns = [
			{
				title: `问题`,
				width: 'calc(20vw)',
				dataIndex: 'question',
				render(item) {
					return (
						// <div className={styles.wtbj}>{item}</div>
						<div className={styles.wtbj} dangerouslySetInnerHTML={{ __html: item }}></div>
					);
				},
			},
			{
				title: '询问次数',
				width: 160,
				align: 'center',
				dataIndex: 'count',
				sorter: (a, b) => a.count - b.count,
				// sortOrder: this.state.sortOrder
			},
			{
				title: '最近询问时间',
				width: 240,
				align: 'center',
				dataIndex: 'createTime',
				sorter: (a, b) => a.createTime - b.createTime,
				// sortOrder: this.state.sortOrder
				render: dataIndex => {
					return moment(dataIndex).format('YYYY-MM-DD HH:mm:ss');
				},
			},
			{
				title: '操作',
				width: 320,
				align: 'center',
				render: (text, row) => {
					return (
						<div className={styles.wt}>
							<Button type="primary" icon="link" size="small" onClick={() => this.openRelatedModal(row.question, row.id)}>关联</Button>
							<Button type="primary" size="small" icon="plus" onClick={() => this.newlyAdded(row)}>新增</Button>
							{this.state.electb === 'false' ? (
								<Button type="primary" icon="eye-invisible" size="small" onClick={() => this.ignore(row)}>忽略</Button>
							) : (
								<Button type="primary" size="small" onClick={() => this.recovery(row)}><MyIcon type="icon-huifu" />恢复</Button>
							)}
							<Button type="primary" size="small" onClick={() => this.getChatRecords(row)}>会话记录</Button>
						</div>
					);
				},
			},
		];

		return (
			<Spin spinning={this.state.login}>
				<Table
					className="zdyTable"
					rowSelection={rowCheckSelection}
					columns={columns}
					dataSource={this.state.dataSource} //数据
					onChange={this.handleChange}
					scroll={{ y: 587 }}
					pagination={false}
				/>
				{Number(this.state.total) > 10 ? (
					<Pagination
						style={{ textAlign: 'right', marginTop: 16 }}
						total={Number(this.state.total)}
						pageSize={this.state.pageSize}
						current={this.state.page}
						// pageSizeOptions={['15', '30', '50', '100']}
						// showSizeChanger={true}
						showQuickJumper={true}
						onChange={this.onChangeA}
						// onShowSizeChange={this.onShowSizeChangeA}
					/>
				) : null}
			</Spin>
		);
	};

	onChangeA = val => {
		// 页数选择
		this.setState({ page: val });
		const { page, pageSize, order, asc } = this.state;
		this.fetch(this.state.seek, this.state.break, this.state.beginTime, this.state.overTime, val, pageSize, order, asc);
	};

	// 每页显示多少条数据
	onShowSizeChangeA = (current, pageSize) => {
		this.setState({ page: current, pageSize: pageSize });
		setTimeout(() => {
			const { order, asc } = this.state;
			this.fetch(this.state.seek, this.state.break, this.state.beginTime, this.state.overTime, current, pageSize, order, asc);
		}, 1);
	};

	handleRelete = () => {
		let rows = this.state.selectedRows;
		if (this.state.break === false) {
			// 忽略
			if (rows) {
				let its = [];
				rows.map(item => {
					its.push(item.question);
				});
				Modal['confirm']({
					title: '忽略问题',
					content: '确定忽略吗？',
					okText: '确认',
					cancelText: '取消',
					onOk: () => {
						const { page, pageSize, order, asc, dataSource } = this.state;
						const { dispatch } = this.props;
						this.reqRef = requestAnimationFrame(() => {
							dispatch({
								type: 'waitingLearningIssue/fetchMn',
								payload: { questions: its, ignored: this.state.portJudge },
								callback: res => {
									message['success'](`${res.msg}`);
									//判断是否需要加载上一页数据 2022.4.8
									const newCurrent = tableDataCheck(dataSource, page, its)
									this.setState({ page: newCurrent }, () => {
										setTimeout(() => {
											this.fetch(this.state.seek, this.state.break, this.state.beginTime, this.state.overTime, newCurrent, pageSize, order, asc);
										}, 1);
									})
								},
							});
						});
					},
					onCancel() { },
				});
			} else {
				message['error']('您还没有选择！');
			}
		} else if (this.state.break === true) {
			if (rows) {
				let its = [];
				rows.map(item => {
					its.push(item.question);
				});
				const { dispatch } = this.props;
				const { page, pageSize, order, asc, dataSource } = this.state;
				this.reqRef = requestAnimationFrame(() => {
					dispatch({
						type: 'waitingLearningIssue/fetchMn',
						payload: { questions: its, ignored: this.state.portJudge },
						callback: res => {
							message['success'](`${res.msg}`);
							//判断是否需要加载上一页数据 2022.4.8
							const newCurrent = tableDataCheck(dataSource, page, its)
							this.setState({ page: newCurrent }, () => {
								setTimeout(() => {
									this.fetch(this.state.seek, this.state.break, this.state.beginTime, this.state.overTime, newCurrent, pageSize, order, asc);
								}, 1);
							})
						},
					});
				});
			} else {
				message['error']('您还没有选择！');
			}
		}
	};
}
export default connect(({ user }) => ({
	// 全局数据 portJudge
	currentUser: user.currentUser,
}))(Form.create()(ModelGeneration));
